package com.lincoln.util;

import java.util.Iterator;

/**
 * 队列
 *
 * @param <Item>
 */
public class ResizingArrayStack<Item> implements Iterable<Item> {
    // 数据池
    private Item[] a = (Item[]) new Object[1];
    // 长度
    private int N = 0;

    /**
     * 是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return N == 0;
    }

    /**
     * 数据长度
     *
     * @return
     */
    public int size() {
        return N;
    }

    public Item[] data() {
        return a;
    }

    /**
     * 重定义长度
     *
     * @param max
     */
    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++) {
            if (i == max) {
                break;
            }
            temp[i] = a[i];
        }
        a = temp;
        N = max;
    }

    /**
     * 入栈
     *
     * @param item
     */
    public void push(Item item) {
        resize(N + 1);
        a[N - 1] = item;
    }

    /**
     * 出栈
     *
     * @return
     */
    public Item pop() {
        if (N == 0) {
            return null;
        } else if (N == 1) {
            Item res = a[0];
            a[0] = null;
            resize(0);
            return res;
        }
        Item[] news = (Item[]) new Object[N - 1];
        Item res = a[0];
        for (int i = 0; i < N - 1; i++) {
            news[i] = a[i + 1];
        }
        a = news;
        N = N - 1;
        return res;
    }

    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }

    @Override
    public String toString() {
        String res = "";
        for (Item b : a) {
            if (b instanceof Byte) {
                res += Integer.toHexString((Byte) b) + ",";
            } else {
                res += b.toString() + ",";
            }
        }
        res = res.substring(0, res.length() - 1);
        return res;
    }

    private class ReverseArrayIterator implements Iterator<Item> {
        private int i = N;

        @Override
        public boolean hasNext() {
            return i > 0;
        }

        @Override
        public Item next() {
            return a[--i];
        }
    }
}
